package com.woniuxy.woniubookmanager.utils;

import io.jsonwebtoken.*;

import java.util.Date;

public class JwtUtils {
    private static String secret = "woniuQAZwsxERTYGV&*^%IJNLkhjg";

    public static String createToken(String account,long minite){
        JwtBuilder jwtBuilder = Jwts.builder();
        //设置 头部
        jwtBuilder.setHeaderParam("alg","HS256");
        jwtBuilder.setHeaderParam("typ","JWT");
        //设置载荷
        jwtBuilder.setIssuer("wugd");
        jwtBuilder.setSubject("蜗牛书店");
        long expire = minite*60*1000;
        jwtBuilder.setExpiration(new Date(new Date().getTime()+expire));
        //自定义信息
        jwtBuilder.claim("account",account);
        /*jwtBuilder.claim("account","wucong");
        jwtBuilder.claim("account","wucong");
        jwtBuilder.claim("account","wucong");
*/
        //设置 签名
        jwtBuilder.signWith(SignatureAlgorithm.HS256,secret);
        //生成token

        String token = jwtBuilder.compact();
        System.out.println(token);
        return token ;
    }

    public static Claims parseToken(String token){
        JwtParser  parser = Jwts.parser();
        Jws<Claims> claimsJws = parser.setSigningKey(secret).parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        return body ;
    }

    /**
     * 返回用户名
     * @param token
     * @return
     */
    public static String getAccount(String token){
        try {
            JwtParser  parser = Jwts.parser();
            Jws<Claims> claimsJws = parser.setSigningKey(secret).parseClaimsJws(token);
            Claims body = claimsJws.getBody();

            return (String) body.get("account");
        }catch (IllegalArgumentException e){
            System.out.println("token参数有问题！");
            e.printStackTrace();
            return null;
        }catch (Exception e){
            System.out.println("系统错误！");
            e.printStackTrace();
            return null;
        }
    }

}
